package com.zcah.db.dbsource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zcah.common.util.JsonUtils;
import com.zcah.db.DbSource;
import com.zcah.db.domain.DbsourceDO;

public abstract class AbstractDbSource implements DbSource {

	private static final Logger logger = LoggerFactory.getLogger(AbstractDbSource.class);

	/**
	 * 数据库连接
	 */
	protected Connection connection;

	/**
	 * 数据库连接地址
	 */
	protected String dbUrl;

	/**
	 * 数据库连接用户
	 */
	protected String username;

	/**
	 * 数据库连接密码
	 */
	protected String password;

	/**
	 * 连接失败错误信息
	 */
	protected String errMsg;

	/**
	 * sql，查询数据库表中内容
	 */
	protected static final String SQL_SELECT_TABLE = "SELECT * FROM %s";

	/**
	 * 自动关闭资源
	 */
	@Override
	public void close() throws Exception {
		connection.close();
	}

	@Override
	public String testConnection() {
		return errMsg == null ? "连接成功" : errMsg;
	}

	@Override
	public ResultSet getResultSet(String tableName) {
		ResultSet resultSet = null;
		String[] names = tableName.split("\\.");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < names.length; i++) {
			sb.append("\"").append(names[i]).append("\"");
			if (i != names.length -1) {
				sb.append(".");
			}
		}
		
		String sql = String.format(SQL_SELECT_TABLE, sb.toString());
		try {
			// 关闭connection时关闭statement
			Statement statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
			// 性能提升明显，对服务器内存要求较高
			statement.setFetchSize(10000);
			statement.setQueryTimeout(3600);
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
		}
		return resultSet;
	}

	/**
	 * 初始化数据库连接参数
	 * 
	 * @param db
	 * @return
	 */
	protected Map<String, String> initSource(DbsourceDO db) {
		username = db.getUsername();
		password = db.getPassword();
		if (db.getParameters() == null) {
			return null;
		}
		try {
			return JsonUtils.toMap(db.getParameters(), String.class, String.class);
		} catch (IOException e) {
			throw new IllegalArgumentException("非法json字符串参数：" + db.getParameters());
		}
	}

	/**
	 * 执行sql获取ResultSet
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	protected ResultSet getSqlResultSet(String sql) throws SQLException {
		Statement statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
		// 性能提升明显，对服务器内存要求较高
		statement.setFetchSize(10000);
		statement.setQueryTimeout(600);
		return statement.executeQuery(sql);
	}

}
